package org.linlinjava.litemall.wx.web;

import jodd.datetime.TimeUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//import org.apache.poi.ss.usermodel.Cell;
//import org.apache.poi.ss.usermodel.Row;
//import org.apache.poi.ss.usermodel.Sheet;
//import org.apache.poi.ss.usermodel.Workbook;
//import org.apache.poi.xssf.usermodel.XSSFRow;
//import org.apache.poi.xssf.usermodel.XSSFSheet;
//import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.linlinjava.litemall.core.util.DateTimeUtil;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.LitemallCdkeyService;
import org.linlinjava.litemall.db.service.LitemallFootprintService;
import org.linlinjava.litemall.db.service.LitemallGoodsService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.WxCdkeyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 兑换码兑换
 */
@RestController
@RequestMapping("/wx/cdkey")
@Validated
public class WxCdkeyController {
    private final Log logger = LogFactory.getLog(WxCdkeyController.class);

    @Autowired
    private LitemallCdkeyService cdkeyService;

    @Autowired
    private WxCdkeyService wxCdkeyService;
    @Autowired
    private LitemallUserService userService;

    private Object validate(LitemallCdkey cdkey){
        if(cdkey == null){
            return ResponseUtil.fail(401, "兑换码未找到");
        }else if(cdkey.getMemberId() != null){
            return ResponseUtil.fail(401, "兑换码已被使用");
        }

        return null;
    }

    /**
     * 兑换码详情
     *
     * @param userId   用户ID
     * @param code 兑换码
     * @return 操作结果
     */
    @GetMapping("detail")
    public Object detail(@LoginUser Integer userId, String code) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        code = code.toUpperCase();
        LitemallCdkey cdkey = cdkeyService.queryByCode(code);
        Object error = validate(cdkey);
        if(error != null){
            return error;
        }
        Map<String, Object> data = new HashMap<>();
        data.put("companyName", cdkey.getCompanyName());
        data.put("code", cdkey.getCode());
        data.put("faceValue", cdkey.getFaceValue());
        data.put("createdTime", cdkey.getAddTime());
        data.put("expiredTime", cdkeyService.getExpiredTime(cdkey));
        return ResponseUtil.ok(data);
    }

    /**
     * 兑换码兑换
     *
     * @param userId   用户ID
     * @return 操作结果
     */
    @RequestMapping("submit")
    public Object submit(@LoginUser Integer userId, @RequestBody String body) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        String code = JacksonUtil.parseString(body, "code");
        code = code.toUpperCase();
        LitemallCdkey cdkey = cdkeyService.queryByCode(code);
        Object error = validate(cdkey);
        if(error != null){
            return error;
        }
        wxCdkeyService.conversion(userId, cdkey);
        return ResponseUtil.ok();
    }


    public boolean useCdkey(String phone){
        System.out.println("正在查找手机号" + phone);
        List<LitemallUser> users = userService.queryByMobile(phone);
        if(users.size() > 0){
            System.out.println("已找到用户" + users.get(0).getId());
            LitemallUser user = users.get(0);
            List<LitemallCdkey> keys = cdkeyService.queryByUserId(user.getId());
            if(keys.size() == 0){
                List<LitemallCdkey> validKeys = cdkeyService.queryByStatus(false);
                if(validKeys.size() > 0){
                    LitemallCdkey key = validKeys.get(0);
                    wxCdkeyService.conversion(user.getId(), key);
                    System.out.println(phone + "    已导入积分");
                    return true;
                }
            }
        }
        return false;
    }
//    @RequestMapping("data")
//    public void data(){
//        List<String> users = new ArrayList<>();
//        InputStream fis = null;
//        String importPath = "/Users/zhiyong/Documents/userList1.xlsx";
//        try {
//            fis = new FileInputStream(importPath);
//            Workbook workbook = null;
//            if (importPath.endsWith(".xlsx")) {
//                workbook = new XSSFWorkbook(fis);
//            } else if (importPath.endsWith(".xls") || importPath.endsWith(".et")) {
//                workbook = new HSSFWorkbook(fis);
//            }
//            fis.close();
//            /* 读EXCEL文字内容 */
//            // 获取第一个sheet表，也可使用sheet表名获取
//            Sheet sheet = workbook.getSheetAt(0);
//            // 获取行
//            int rowNum = sheet.getLastRowNum() + 1;
//            for (int j = 0; j < rowNum; j++) {
//                if(j > 1) {
//                    Row row = sheet.getRow(j);
//                    if (row != null) {
//                        users.add(row.getCell(2).toString());
//                    }
//                }
//            }
//
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            if (null != fis) {
//                try {
//                    fis.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        List<String> importData = new ArrayList<>();
//        for (String telephone: users
//        ) {
//            if(useCdkey(telephone)){
//                importData.add(telephone);
//            }
//        }
//
//        createSheets(importData);
//    }
//
//    private void createSheets(List<String> users){
//        XSSFWorkbook workbook = new XSSFWorkbook();
//        XSSFSheet sheet = workbook.createSheet();
//        for (int i = 0; i < users.size(); i++) {
//            XSSFRow row = sheet.createRow(i);
//            Cell userNameCell = row.createCell(1);
//            userNameCell.setCellValue(users.get(i));
//        }
//
//        try {
//            FileOutputStream fileOut = new FileOutputStream("/Users/zhiyong/Documents/testaaa" + ".xlsx");
//            workbook.write(fileOut);
//            fileOut.close();
//            workbook = null;
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}